package at.fpmedv.eclipse.helma.core;

import helma.framework.repository.Resource;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.Iterator;

import at.fpmedv.eclipse.helma.util.ResourceContainer;

/**
 * represents a pice of code in the tree view
 * 
 * @author fpm
 * 
 */
public class FunctionTreeObject implements ITreeObject {
	
	/**
	 * name of this function
	 */
	private String functionName;
	
	/**
	 * always a prototype
	 */
	private ITreeParent parent;

	public FunctionTreeObject(String propertyName,
			ITreeParent parentPrototypeTreeObject) {
		functionName = propertyName;
		this.parent = parentPrototypeTreeObject;
	}

	public Object getAdapter(Class key) {
		return null;
	}

	public String getName() {
		return functionName;
	}

	public String getRawName() {
		String result = getName();
		if (result.startsWith("__")) {
			result = result.replaceAll("^__(.+)__$", "$1");
		}
		return result;
	}

	public ITreeParent getParent() {
		return parent;
	}

	public String toString() {
		return getName();
	}

	public ResourceContainer getResource() {
		Resource result = null;
		int resultLineNumber = 1;
		for (Iterator<Resource> iterRes = parent.getResources().iterator(); iterRes.hasNext();) {
			Resource res = iterRes.next();
			if (res.getName().endsWith(".js")) {
				BufferedReader codeReader;
				try {
					InputStream in = res.getInputStream();
					codeReader = new BufferedReader(new InputStreamReader(in));
					int lineNr = 1;
					String line = "";
					while ((line = codeReader.readLine()) != null) {
						if (line.contains("." + this.getRawName() + " ") || line.contains("ion " + this.getRawName())) {
							result = res;
							resultLineNumber = lineNr;
						}
						lineNr++;
					}
					in.close();
				} catch (IOException e) {
					HelmaCorePlugin.getDefault().log("error reading Resource " + res.toString(), e);
					continue;
				}
			}
		}
		return new ResourceContainer(result, resultLineNumber);
	}

	public int compare(ITreeObject element, Comparator comparator) {
		// sort by name
		if (element instanceof FunctionTreeObject)
			return comparator.compare(this.getName(), element.getName());
		// greater than skins
		if (element instanceof SkinTreeObject)
			return -1;
		// smaller than everything else
		return 1;

	}
}
